// pages/guide-detail/guide-detail
Page({
  data: {
    backendUrl: 'http://127.0.0.1:88/api/user/',
    guide: null 
  },

  onLoad(options) {
    const guideId = options.id;
    const userInfo = wx.getStorageSync('userInfo');
    this.loadGuideDetail(guideId, userInfo?.id);
  },

  // 加载指南详情
  loadGuideDetail(id, userId) {
    wx.request({
      url: this.data.backendUrl + 'get_guide_detail.php',
      data: { 
        id: id,
        user_id: userId 
      },
      success: (res) => {
        if (res.data.status === 'success') {
          this.setData({
            guide: res.data.guide
          });
          // 设置页面标题
          wx.setNavigationBarTitle({
            title: res.data.guide.title
          });
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      }
    });
  },

  // 收藏/取消收藏
  toggleFavorite() {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    const action = this.data.guide.is_favorite ? 'remove' : 'add';
    
    wx.request({
      url: this.data.backendUrl + 'toggle_favorite.php',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        user_id: userInfo.id,
        guide_id: this.data.guide.id,
        action: action
      },
      success: (res) => {
        if (res.data.status === 'success') {
          // 更新本地收藏状态
          this.setData({
            'guide.is_favorite': !this.data.guide.is_favorite
          });
          wx.showToast({
            title: res.data.message,
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          });
        }
      }
    });
  },

  // 分享功能
  onShareAppMessage() {
    const guide = this.data.guide;
    if (!guide) return;
    return {
      title: guide.title,
      path: `/pages/guide-detail/guide-detail?id=${guide.id}`,
      imageUrl: this.data.backendUrl + guide.cover_image
    };
  }
}); 